<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
class Purchaselogic{
	/**
     * 采购单申请列表
     * @param int 	 $user_id  操作用户ID
     * @param string start_time 			开始时间
	 * @param string end_time   			结束时间
	 * @param int supplier_id				供应商id
	 * @param int procurement_method		采购方式
	 * @param int arrival_warehouse_id		仓库id
	 * @param string handled_by				经办人
	 * @param string code   				采购单号
     * @author shiqiang
     * @return mixed
     */
    public function list($user_id, $title = '', $supplier_id = 0, $procurement_method = 0, $arrival_warehouse_id = 0, $handled_by = '', $code = '', $status = ''){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 				=> $user_id,
				'title' 				=> $title,
				'supplier_id' 			=> $supplier_id,
				'procurement_method' 	=> $procurement_method,
				'arrival_warehouse_id' 	=> $arrival_warehouse_id,
				'handled_by' 			=> $handled_by,
				'code' 					=> $code,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/

            $map = [];//搜索处理
            if($supplier_id > 0) 			$map[] = ['supplier_id', '=', $supplier_id];
            if($procurement_method > 0) 	$map[] = ['procurement_method', '=', $procurement_method];
            if($arrival_warehouse_id > 0) 	$map[] = ['arrival_warehouse_id', '=', $arrival_warehouse_id];
            if($title != '') 				$map[] = ['title', 'like', '%'. $title .'%'];
            if($code != '') 				$map[] = ['code', 'like', '%'. $code .'%'];
			if($handled_by != '') 			$map[] = ['handled_by', 'like', '%'. $handled_by .'%'];
			if($status) 					$map[] = ['purchase_status', '=', $status];
			
			$list = model('ErpGoodsPurchaseOrder', 'model') -> where($map) -> order('create_time desc') -> paginate();
			$rel_list = [];
            foreach($list as $key => $value){
				$rel_list[$key]['id'] 					= (int)$value['id'];
				$rel_list[$key]['title'] 				= (string)$value['title'];
				$rel_list[$key]['supplier'] 			= (string)$value['get_erp_supplier']['title']; //供应商
				$rel_list[$key]['procurementMethod'] 	= (string)$value['procurement_method'] == 1 ? '现购' : '赊购';
				$rel_list[$key]['arrivalWarehouse'] 	= (string)$value['get_erp_warehouse']['title'];//仓库
				$rel_list[$key]['advanceCharge'] 		= (string)$value['advance_charge']; 		//预付款
				$rel_list[$key]['arrivalDays'] 			= (int)$value['arrival_days']; 				//到货天数
				$rel_list[$key]['remark'] 				= (string)$value['remark']; 				//备注
				$rel_list[$key]['handledBy'] 			= (string)$value['handled_by']; 			//经办人
				$rel_list[$key]['code'] 				= (string)$value['code'];
				$rel_list[$key]['status'] 				= (int)$value['purchase_status'];
				$rel_list[$key]['createTime'] 			= (int)$value['create_time'];
			}
			$result_list = [];
			$result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
			$result_list['data'] 			= $rel_list;
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 申请采购
	 * @param int  		user_id				
	 * @param string  	title				
	 * @param int		supplier_id			 供应商id
	 * @param int 		procurement_method	 采购方式 1现购 2赊购
	 * @param int		arrival_warehouse_id 到货仓id
	 * @param string 	advance_charge		 预付款
	 * @param int 		arrival_days		 到货天数
	 * @param string	remark				 备注
	 * @param string 	handled_by			 经办人
	 * @param array 	purchase_sku		 采购sku
	 * @param int 		sku_id		 		 采购sku - sku_id
	 * @param int 		num		 		 	 采购sku - 数量
	 * @param string 	price		 		 采购sku - 价格
     * @author shiqiang
     * @return mixed
     */
	public function add($user_id, $title, $supplier_id, $procurement_method, $arrival_warehouse_id, $advance_charge, $arrival_days, $remark, $handled_by, $purchase_sku){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 				=> $user_id,
				'title' 				=> $title,
				'supplier_id' 			=> $supplier_id,
				'procurement_method' 	=> $procurement_method,
				'arrival_warehouse_id' 	=> $arrival_warehouse_id,
				'advance_charge' 		=> $advance_charge,
				'arrival_days' 			=> $arrival_days,
				'remark' 				=> $remark,
				'handled_by' 			=> $handled_by,
				'purchase_sku' 			=> $purchase_sku,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$order_num = model('ErpGoodsPurchaseOrder', 'model') -> count();
			$order_num = $order_num + 1;
			$code = 'P' . date('Ymd') . str_pad($order_num, 3, '0', STR_PAD_LEFT);//拼接code  规则 P + 日期 + 流水号 (本日订单总数 + 1) 3位数 补0
			$rel = model('ErpGoodsPurchaseOrder', 'model') -> addData($user_id, $title, $supplier_id, $procurement_method, $arrival_warehouse_id, $advance_charge, $arrival_days, $remark, $handled_by, $code);
			if($rel['code'] < 0){
				DB::rollback();
				return array_out(-1005, 'error'); // 插入失败
			}
			
			//插入采购单 sku参数
			$sku_arr = [];
			$purchase_id = $rel['data'];
			foreach($purchase_sku as $key => $value){
				$sku_arr[] = [
					'purchase_id' => $purchase_id,
					'sku_id'	  => $value['sku_id'],
					'num'	  	  => $value['num'],
					'price'	  	  => $value['price'],
				];
			}
			$rel = model('ErpGoodsPurchaseOrderSku') -> saveAll($sku_arr);//dump($rel);
			if(!$rel < 0){
				DB::rollback();
				return array_out(-1005, 'error2');
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    } 
	
	/**
     * 采购单详情
     * @param int 	 $user_id  操作用户ID
     * @author shiqiang
     * @return mixed
     */
    public function details($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$info = model('ErpGoodsPurchaseOrder', 'model') -> where('id', $id) -> find();
			$rel_list = [];
			if(!empty($info)){
				$rel_list['id'] 				= (int)$info['id'];
				$rel_list['title'] 				= (string)$info['title'];
				$rel_list['supplier'] 			= (string)$info['get_erp_supplier']['title']; //供应商
				$rel_list['procurementMethod'] 	= (string)$info['procurement_method'] == 1 ? '现购' : '赊购';
				$rel_list['arrivalWarehouse'] 	= (string)$info['get_erp_warehouse']['title'];//仓库
				$rel_list['advanceCharge'] 		= (string)$info['advance_charge']; 		//预付款
				$rel_list['arrivalDays'] 		= (int)$info['arrival_days']; 				//到货天数
				$rel_list['remark'] 			= (string)$info['remark']; 				//备注
				$rel_list['handledBy'] 			= (string)$info['handled_by']; 			//经办人
				$rel_list['code'] 				= (string)$info['code'];
				$rel_list['status'] 			= (int)$info['purchase_status'];
				$rel_list['createTime'] 		= (int)$info['create_time'];
				
				$purchase_sku = [];
				$order_sku = model('ErpGoodsPurchaseOrderSku', 'model') -> where('purchase_id', $id) -> column('id,sku_id,num,price');
				foreach($order_sku as $key => $value){
					$sku_id = $value['sku_id'];
					$goods_name = model('ErpGoodsSku', 'model') -> where('id', $sku_id) -> find() -> goods_name;//sku信息
					
					$purchase_sku[] = [
						'purchaseSkuId' => $value['sku_id'],
						'goodsName'  	=> $goods_name,
						'num' 			=> $value['num'],
						'price' 	 	=> $value['price'],
					];
				}
				$rel_list['purchaseSku'] 	 = (array)$purchase_sku;
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $rel_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
}